const base = require('./base'),
    tool = require('../../utils/common'),
    md5 = require('md5-node'),
    uuid = require('uuid');

class user extends base {
    USER_TYPE_1 = 1;
    USER_TYPE_10 = 10;
    _createTime = 'create_time';
    _updateTime = 'update_time';

    /**
     * 是否登录
     * @returns {boolean}
     */
    static isLogin(req, res) {
        if ('authorization' in req.headers) {
            let token = req.headers.authorization, model = new user();
            return new Promise((resolve, reject) => {
                model.list({
                    "login_token": token,
                    'user_type': model.USER_TYPE_10
                }, 1).then(result => {
                    if (!result || !result.length || !result[0].login_token_expire) {
                        reject({code: 1000, message: '登录失效，请重新登录'});
                        return;
                    }
                    let time = parseInt((new Date()).getTime() / 1000);
                    if (time > result[0].login_token_expire) {
                        reject({code: 1001, message: '登录已过期，请重新登录'});
                        return;
                    }

                    resolve(result[0]);
                }).catch(e => reject(e));
            });
        } else {
            tool.throwError('您没有登录');
        }
    }

    /**
     * 登录操作
     */
    login(username, password) {
        let where = {'username': username};

        return new Promise((resolve, reject) => {
            this.list(where, 1).then(result => {
                //用户是否存在
                if (!result || !result.length) {
                    reject('用户密码错误');
                    return;
                }
                //密码验证
                let pwd = this.encryPwd(password);
                if (result[0]['password'] != pwd) {
                    reject('密码错误');
                    return;
                }

                //生成token
                let token = uuid.v4(), expire = parseInt((new Date()).getTime() / 1000 + 7200);
                this.update({'login_token': token, 'login_token_expire': expire}, {id: result[0].id}).then(result => {

                }).catch(e => reject(e))

                result[0].login_token = token;
                result[0].login_token_expire = expire;
                resolve(result[0]);
            }).catch(e => reject(e));
        });
    }

    /**
     * 注册操作
     */
    register(data) {

    }

    encryPwd(pwd, salt = '') {
        return md5(md5(pwd) + salt);
    }
}

module.exports = user;